﻿using System;
using System.Collections.Generic;
using System.Text;

namespace AutoUpdate.Utility.Helper
{
    using System.IO;
    public class FileHelper
    {
        public static byte[] fileRead(string fileName, long offset, int length, out int readLength)
        {
            byte[] result = null;

            try
            {
                readLength = 0;

                result = new byte[length];

                using (FileStream fsRead = new FileStream(fileName, FileMode.Open))
                {
                    fsRead.Seek(offset, SeekOrigin.Begin);

                    readLength = fsRead.Read(result, 0, length);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return result;
        }

        public static void fileWrite(string fileName, long offset, int length, byte[] buffer)
        {
            try
            {
                if (File.Exists(fileName))
                {
                    using (FileStream fsWrite = new FileStream(fileName, FileMode.Open))
                    {
                        fsWrite.Seek(offset, SeekOrigin.Begin);

                        fsWrite.Write(buffer, 0, length);
                    }
                }
                else
                {
                    using (FileStream fsWrite = new FileStream(fileName, FileMode.Create))
                    {
                        fsWrite.Seek(offset, SeekOrigin.Begin);

                        fsWrite.Write(buffer, 0, length);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static string fileMd5(string filePath)
        {
            string result = string.Empty;

            try
            {
                using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    using (System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
                    {
                        byte[] value = md5.ComputeHash(fileStream);

                        result = BitConverter.ToString(value);

                        result = result.Replace("-", "");
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return result;
        }

        public static string[] getSubDirectories(string path)
        {
            return Directory.GetDirectories(path);
        }

        public static string[] getSubFiles(string path)
        {
            return Directory.GetFiles(path);
        }
    }
}
